package up.android.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Method;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * Servlet implementation class Calculadora
 */
@WebServlet("/Calculadora")
public class Calculadora extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Calculadora() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		InputStreamReader reader = new InputStreamReader(request.getInputStream());
		BufferedReader b = new BufferedReader(reader);
		String s = "";
		String line;
		while((line = b.readLine())!= null)
			s+=line+"\n";

		try {
			JSONObject obj = new JSONObject(s);
			
			String action = obj.getString("action");
			Method m = Calculadora.class.getMethod(action,new Class[]{JSONObject.class});
			JSONObject result = (JSONObject)m.invoke(this, new Object[]{obj});
		
			response.getWriter().print(result.toString());
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	@SuppressWarnings("unused")
	public JSONObject sum(JSONObject arg) throws JSONException
	{
		int a = arg.getInt("par1");
		int b = arg.getInt("par2");
		JSONObject retVal = new JSONObject();
		retVal.put("result", a+b);
		return retVal;
	}
	
	public JSONObject save(JSONObject arg) throws JSONException
	{
		int a = arg.getInt("par1");
		JSONObject retVal = new JSONObject();
		retVal.put("result",a);
		return retVal;
	}

}
